﻿Imports System.Net
Imports System.IO
Imports System.Text.RegularExpressions

Public Class ImageSave

    Private _retimg As Image
    Public Property ReturnedImage() As Image
        Get
            Return _retimg
        End Get
        Set(ByVal value As Image)
            _retimg = value
        End Set
    End Property

    Private _retimgpath As String
    Public Property ReturnedImagePath() As String
        Get
            Return _retimgpath
        End Get
        Set(ByVal value As String)
            _retimgpath = value
        End Set
    End Property

    Private _aspng As Boolean
    Public Property MakePNG() As Boolean
        Get
            Return _aspng
        End Get
        Set(ByVal value As Boolean)
            _aspng = value
        End Set
    End Property

    Private _safefilename As String
    Public Property SafeFilename() As String
        Get
            Return _safefilename
        End Get
        Set(ByVal value As String)
            _safefilename = value
        End Set
    End Property





    '===============================================================================
    'Public Vars
    Public ImgHTML As HtmlElementCollection
    Public ImgDT As New DataTable

    Public GameNames As New List(Of String)
    Public Filenames As New Dictionary(Of String, String)
    Public Filepaths As New List(Of KeyValuePair(Of String, String))


    '===============================================================================

    Private Sub ImageSave_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Debug.WriteLine(vbCr & "===========================WEB IMAGE SAVE================================" & vbCr)
        Me.Show()
        Me.Refresh()

        Call MainRoutine()
    End Sub

    Public Sub MainRoutine()
        '===============================================================================
        'SET INHERITED VARIABLES
        '===============================================================================
        ImgHTML = GameSetMatch.hecImages
        '===============================================================================
        'DGV
        Call ImgTableSetup()
        Call ImportImgElements()
        Call PopulateImgDGV()
        ImgsDGV.Columns("URLFilename").AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
        ImgsDGV.Columns("URL").AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader

    End Sub

    Sub PopulateImgDGV()
        With ImgsDGV
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            ' .ReadOnly = True
            .RowTemplate.Height = 100
            .DataSource = ImgDT
            .Columns.Add(New DataGridViewImageColumn With {.Name = "Image",
                                                           .Visible = True,
                                                           .Image = My.Resources.no_image,
                                                           .AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
                                                           .ImageLayout = DataGridViewImageCellLayout.Zoom,
                                                           .Width = 200,
                                                           .DisplayIndex = 1})
            .Columns("URLFileExt").DisplayIndex = 2
            .Columns("Width").DisplayIndex = 3
            .Columns("Height").DisplayIndex = 4
            .Columns("URLFilename").DisplayIndex = 5
            .Columns("URLFilename").AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
            .Columns("URL").AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
            .Sort(ImgsDGV.Columns("URL"), System.ComponentModel.ListSortDirection.Ascending)
        End With

        For Each column As DataGridViewColumn In ImgsDGV.Columns
            If column.Name = "Select" Then
                'MsgBox("here!")
            Else
                column.ReadOnly = True
            End If
        Next



        ImgDT.Rows(0).Item("Select") = True
        'PopulateGridIMages()

    End Sub

    Sub RepopImgsOnSort(ByVal sender As Object, ByVal e As System.EventArgs) Handles ImgsDGV.Sorted
        PopulateGridIMages()
    End Sub

    Sub PopulateGridIMages()
        Dim client As New Net.WebClient
        Dim url As String = String.Empty
        With ProgressBar1
            .Minimum = 0
            .Maximum = ImgDT.Rows.Count - 1
            .Value = 0
        End With

        For i As Integer = 0 To ImgDT.Rows.Count - 1
            ProgressBar1.Value = i
            url = ImgDT.Rows(i).Item("URL")
            Try
                ImgsDGV.Rows(i).Cells("Image").Value = New Bitmap(New IO.MemoryStream(client.DownloadData(url)))
            Catch
                ImgsDGV.Rows(i).Cells("Image").Value = My.Resources.no_image
            End Try
        Next
    End Sub


    Sub ImgTableSetup()
        With ImgDT
            .Columns.Add("Select", GetType(Boolean))
            .Columns.Add("URL", GetType(String))
            .Columns.Add("URLFilename", GetType(String))
            .Columns.Add("URLFileExt", GetType(String))
            .Columns.Add("Width", GetType(Integer))
            .Columns.Add("Height", GetType(Integer))
            .Columns.Add("Size", GetType(Integer))
        End With
    End Sub

    Sub ImportImgElements()
        Debug.WriteLine("--------Populate Data Table----------")
        Debug.WriteLine("Total Items: " & ImgHTML.Count - 1)
        Dim ImageURL As String

        Dim ImageExtention As String
        Dim ImageFilename As String
        Dim ImageSize As Integer
        Dim ImageWidth As Integer
        Dim ImageHeight As Integer

        'Reset Table
        ImgDT.Clear()

        With ProgressBar1
            .Minimum = 0
            .Maximum = ImgHTML.Count - 1
        End With



        For i As Integer = 0 To ImgHTML.Count - 1 'Loop Through All IMG Elements Found
            ProgressBar1.Value = i
            ImageURL = ImgHTML(i).GetAttribute("src").ToString
            'Chekc URL against src tag
            Debug.WriteLine("ITERATION: {0}. {1}", i, ImageURL)

            'If Not CheckAddress(ImageURL, Nothing) Then
            '    Debug.WriteLine("Not valid URL. Skipping to next iteration.")
            '    Continue For
            'End If

            ImageExtention = System.IO.Path.GetExtension(ImageURL)
            If ImageExtention = "" Then
                Debug.WriteLine("No Image extention. Using .png default")
                ImageExtention = ".png"
            End If

            ImageFilename = System.IO.Path.GetFileNameWithoutExtension(ImageURL)
            Debug.WriteLine("Ext: " & ImageExtention)
            Debug.WriteLine("File: " & ImageFilename)

            ImageSize = 0
            Debug.WriteLine("Size: " & ImageSize / 1000 & "K")

            ImageWidth = ImgHTML(i).GetAttribute("width")
            ImageHeight = ImgHTML(i).GetAttribute("height")
            Debug.WriteLine("Width: " & ImageWidth)
            Debug.WriteLine("Height: " & ImageHeight)

            'Add Datarow
            ImgDT.Rows.Add(False, ImageURL, ImageFilename, ImageExtention, ImageWidth, ImageHeight, ImageSize)
            Debug.WriteLine("-------------------------------------------------")
        Next

    End Sub

    Private Function CheckAddress(ByVal strUrl As String, _
                                    ByRef strError As String) _
                                    As Boolean
        Dim bolResult As Boolean = True

        Try
            Dim request As HttpWebRequest = WebRequest.Create(strUrl)
            request.Method = "HEAD"
            request.Timeout = 1000
            Dim response As HttpWebResponse = request.GetResponse
            If Not response.StatusCode = HttpStatusCode.OK Then
                bolResult = False
                strError = response.StatusCode.ToString()
            End If
        Catch ex As Exception
            bolResult = False
            strError = "Exception: " & ex.ToString()
        End Try

        Return bolResult
    End Function

    'Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles ImgsDGV.CellContentClick
    '    If e.ColumnIndex = ImgsDGV.Columns("Select").Index Then
    '        DataGridViewCheckBoxColumn_Uncheck()
    '        Dim cell As DataGridViewCheckBoxCell = ImgsDGV.Rows(e.RowIndex).Cells("Select")
    '        cell.Value = True
    '        ImgsDGV.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightGreen
    '    End If
    'End Sub

    'Private Sub DataGridViewCheckBoxColumn_Uncheck()
    '    For Each row As DataGridViewRow In ImgsDGV.Rows
    '        If row.Cells("Select").Value = True Then
    '            row.Cells("Select").Value = False
    '            row.DefaultCellStyle.BackColor = Color.White
    '        End If
    '        'Dim cell As DataGridViewCheckBoxCell = row.Cells("Select")
    '        'cell.Value = False
    '    Next
    'End Sub



    'Private Sub CheckboxChanged(sender As Object, e As EventArgs) Handles ImgsDGV.CurrentCellDirtyStateChanged
    '    Debug.WriteLine("Checkbox")

    '    If ImgsDGV.IsCurrentCellDirty Then
    '        If Me.ImgsDGV.CurrentCell.Value = False Then
    '            'Update only if changed from false to true
    '            If Me.ImgsDGV.CurrentCell.OwningColumn.Name.Equals("Select") = False Then Me.ImgsDGV.CurrentRow.Cells("ImgsDGV").Value = False
    '            Me.ImgsDGV.CommitEdit(DataGridViewDataErrorContexts.Commit)
    '        Else
    '            'Prevent changes
    '            Me.ImgsDGV.CancelEdit()
    '        End If

    '        'ImgsDGV.CommitEdit(DataGridViewDataErrorContexts.Commit)
    '    End If
    '    ' ImgsDGV.SelectedRows(0).Index
    'End Sub







    'Private Sub dgvNormalReports_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles ImgsDGV.CellClick

    '    If e.ColumnIndex >= 0 And e.ColumnIndex <= ImgsDGV.ColumnCount - 1 And e.RowIndex >= 0 And e.RowIndex <= ImgsDGV.Rows.Count - 1 Then
    '        Select Case ImgsDGV.Columns(e.ColumnIndex).Name
    '            Case "Select" 'mimic radiobutton - turn off other checkboxes
    '                ImgsDGV.Rows(e.RowIndex).Cells("Select").Value = False
    '                'N.B. current cell's checked status is changed AFTER this event
    '            Case Else
    '                'ignore
    '        End Select
    '    End If
    'End Sub




    Private Sub Button2_Click(sender As Object, e As EventArgs)
        Me.Close()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'IMAGE SAVE

        Dim SelRow() As DataRow = ImgDT.Select("Select = True")
        If SelRow.Count < 1 Then
            MsgBox("Please select which image to save by placing a tick in the box...")
            Return
        End If

        If Not Directory.Exists(Path.GetTempPath & "GameSetMatch") Then
            Directory.CreateDirectory(Path.GetTempPath & "GameSetMatch")
        End If

        'delete files if poss
        For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
                Path.GetTempPath & "GameSetMatch", _
                Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.*")
            Try
                My.Computer.FileSystem.DeleteFile(foundFile, _
                    Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, _
                    Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently)
            Catch ex As Exception

            End Try
        Next

        Dim wcObj As New System.Net.WebClient()

        Dim tempfileworking As String = Path.GetTempPath & "GameSetMatch\" & _safefilename & "_WorkingCopy" & SelRow(0).Item("URLFileExt")
        Dim tempfile As String

        Try
            wcObj.DownloadFile(SelRow(0).Item("URL"), tempfileworking)

            If _aspng And Path.GetExtension(tempfileworking) <> ".png" Then
                tempfile = Path.GetDirectoryName(tempfileworking) & "\" & Path.GetFileNameWithoutExtension(tempfileworking) & ".png"
                ConvertImage(tempfileworking, Imaging.ImageFormat.Png, tempfile)
                File.Delete(tempfileworking)
            Else
                tempfile = tempfileworking
                ' File.Copy(tempfileworking, tempfile, True)
            End If

            GameSetMatch.StoredImage = SafeImageFromFile(tempfile)

            GameSetMatch.StoredImgPath = tempfile

        Catch ex As Exception
            MsgBox("Error dowloading from web - please try again or try a different file")
            'CPWBAdmin.Log("Error downlaoding web image: " & vbCr & ex.Message & vbCr & ex.StackTrace)
        End Try

        Me.Close()
    End Sub

    Public Sub ConvertImage(ByVal Filename As String, ByVal DesiredFormat As System.Drawing.Imaging.ImageFormat,
                               ByVal NewFilename As String)

        Debug.WriteLine(">>> CONVERT IMAGE SUB")
        ' Takes a filename and saves the file in a new format
        Try
            Dim imgFile As New Bitmap(SafeImageFromFile(Filename))

            If File.Exists(NewFilename) Then
                File.Delete(NewFilename)
            End If

            imgFile.Save(NewFilename, DesiredFormat)
        Catch ex As Exception
            'log.Log_Error("Whilst converting image to png: " & ex.Message & vbCr & ex.StackTrace)
        End Try
    End Sub

    Public Shared Function RemoveIllegalFileNameChars(input As String, Optional replacement As String = "") As String
        Dim regexSearch As String = New String(Path.GetInvalidFileNameChars()) & New String(Path.GetInvalidPathChars())
        Dim r As Regex = New Regex(String.Format("[{0}]", Regex.Escape(regexSearch)))
        Return r.Replace(input, replacement)
    End Function

    'Private Sub SaveToBrowse_Click(sender As Object, e As EventArgs) Handles SaveToBrowse.Click
    '    With FB1
    '        If Directory.Exists(SaveTo.ValueMember) Then
    '            .SelectedPath = SaveTo.ValueMember
    '        Else
    '            .SelectedPath = MarqueeEditor._DefAssets
    '        End If
    '        '.SelectedPath = MarqueeEditor._DefAssets
    '        .Description = "Choose which folder to save this image to..."
    '    End With
    '    If FB1.ShowDialog() = Windows.Forms.DialogResult.OK Then
    '        Filepaths.Insert(0, New KeyValuePair(Of String, String)("{User Choice}: " & FB1.SelectedPath, FB1.SelectedPath))
    '        SaveTo.DataSource = New BindingSource(Filepaths, Nothing)
    '        SaveTo.SelectedIndex = 0
    '        'SaveTo.DisplayMember = "{User Choice}: " & FB1.SelectedPath
    '    Else
    '        Return
    '    End If
    'End Sub

    Private Sub _SaveIMgsDGVCellClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles ImgsDGV.CellClick
        If e.RowIndex < 0 Or e.ColumnIndex < 0 Then
            Return
        End If
        'MARQUEE DGV CELL DOUBLE CLICK
        Debug.WriteLine("Marquee DGV Cell Click: " & e.RowIndex & ", " & e.ColumnIndex)
        For Each row As DataGridViewRow In ImgsDGV.Rows
            If row.Cells("Select").Value = True Then
                row.Cells("Select").Value = False
                row.DefaultCellStyle.BackColor = Color.White
            End If
        Next
        ImgsDGV.Rows(e.RowIndex).Cells("Select").Value = True
        ImgsDGV.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightGreen
    End Sub

    Private Sub dataGridView1_Sorted(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles ImgsDGV.Sorted
        For Each row As DataGridViewRow In ImgsDGV.Rows
            If row.Cells("Select").Value = True Then
                row.DefaultCellStyle.BackColor = Color.LightGreen
                ImgsDGV.FirstDisplayedScrollingRowIndex = row.Index
            End If
        Next
    End Sub

    Public Shared Function SafeImageFromFile(path As String) As Image
        Using fs As New FileStream(path, FileMode.Open, FileAccess.Read)
            Dim img = Image.FromStream(fs)
            Return img
        End Using
    End Function

End Class